<?php

namespace app\admin\controller;

use app\admin\service\Agent as AgentService;
use app\admin\service\AgentBalanceLog as AgentBalanceLogService;
use app\model\Agent as Model;
use app\model\BaseSupplier;
use app\model\MobileSupplier;
use app\model\ServiceSub;
use app\Request;
use app\common\model\Export;

class AgentNew extends Controller
{
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * @api {GET} /admin/agentNew/ 代理商列表
     */
    public function index(Request $request)
    {
        $where = [['is_deleted', '=', 0]];  // todo 把现有迁移成 deleted_at标识
        $param = input('post.');
        $username = ($param['username'] ?? '');
        if ($username) {
            $where[] = ['username|company_name', 'like', '%' . $username . '%'];
        }
        if (!empty($param['status'])) {
            $where[] = ['status', '=', $param['status']];
        }
        if (isset($param['is_relation'])) {
            $where[] = ['is_relation', '=', $param['is_relation']];
        }
        if (!empty($param['settle_type'])) {
            $where[] = ['settle_type', '=', $param['settle_type']];
        }
        if (isset($param['recharge_amount_max']) && '' != $param['recharge_amount_max']) {
            $where[] = ['recharge_amount', '<=', $param['recharge_amount_max'] * 100];
        }
        if (isset($param['recharge_amount_min']) && '' != $param['recharge_amount_min']) {
            $where[] = ['recharge_amount', '>=', $param['recharge_amount_min'] * 100];
        }
        $createdDate = $param['createdDate'] ?? [];
        if (is_array($createdDate) && !empty($createdDate[0]) && $createdDate[1]) {
            $where[] = ['created_at', 'between time', [$createdDate[0], $createdDate[1] . ' 23:59:59']];
        }
        $sortFields = ['recharge_amount', 'balance', 'withdraw_amount', 'created_at'];
        if (!empty($param['sortField']) && !empty($param['sortOrder'])) {
            if (in_array($param['sortField'], $sortFields)) {
                if ('ascend' == $param['sortOrder']) {
                    $order = $param['sortField'] . ' asc';
                } else {
                    $order = $param['sortField'] . ' desc';
                }
            } else {
                $order = 'id desc';
            }
        } else {
            $order = 'id desc';
        }
        $field = 'username,company_name,mobile,id,status,mobile_discount_fast,mobile_discount_slow,settle_type,created_at,
        recharge_amount, balance, profit_balance, ip_address, mobile_supplier_ids,is_relation,link_type, is_short_chain';
        $query = Model::field($field)
            ->with(['serviceConfig' => function ($query) {
                $query->where('status', 1)->field(['agent_id', 'status', 'serv_type', 'value', 'time_end',
                    'time_begin', 'discount_slow', 'discount_fast', 'agent_lower_price', 'income_type',
                    'discount_slow_all', 'discount_fast_all']);
            },
                'agentSalesman.salesman' => function ($subQuery) {
                    $subQuery->where('is_deleted', DELETE_TYPE_NO);
                }, 'mobileSupplier', 'supplier', 'agentExtend']);
        if ($where) {
            $query = $query->where($where);
        }

        $data = $query->order($order)
            ->paginate($this->getPaginate())
            ->toArray();

        // 把config 转化成列
        if ($data['data']) {
            foreach ($data['data'] as $k => $v) {
                // 处理供应商
                $suppliers = [];
                if (!empty($v['mobileSupplier'])) {
                    $suppliers[PRODUCT_MOBILE_SERV] = array_column($v['mobileSupplier'], 'mobile_supplier_id');
                }
                if (!empty($v['supplier'])) {
                    foreach ($v['supplier'] as $v2) {
                        $suppliers[$v2['serv_type']][] = $v2['supplier_id'];
                    }
                }

                // 业务员
                $salesmanArr = [];
                if (!empty($v['agentSalesman'])) {
                    foreach ($v['agentSalesman'] as $v3) {
                        $salesmanArr[$v3['serv_type']]['salesman_id'] = $v3['salesman_id'];
                        $salesmanArr[$v3['serv_type']]['salesman_true_name'] = $v3['salesman']['true_name'] ?? '';
                    }
                }

                //编辑时候初始化配置
                if ($v['serviceConfig']) {
                    foreach ($v['serviceConfig'] as $k2 => $v2) {
                        //构造form表单config 字段
                        $data['data'][$k]['service_config'][$v2['serv_type']]['income_type'] = $v2['income_type'];
                        $data['data'][$k]['service_config'][$v2['serv_type']]['status'] = $v2['status'];
                        $data['data'][$k]['service_config'][$v2['serv_type']]['discount_slow'] = $v2['discount_slow'];
                        $data['data'][$k]['service_config'][$v2['serv_type']]['discount_fast'] = $v2['discount_fast'];
                        $data['data'][$k]['service_config'][$v2['serv_type']]['discount_slow_all'] = json_decode($v2['discount_slow_all'], true);
                        $data['data'][$k]['service_config'][$v2['serv_type']]['discount_fast_all'] = json_decode($v2['discount_fast_all'], true);
                        $data['data'][$k]['service_config'][$v2['serv_type']]['value'] = $v2['value'];
                        $data['data'][$k]['service_config'][$v2['serv_type']]['agent_lower_price'] = $v2['agent_lower_price'];
                        if (!empty($v2['time_end'])) {
                            $data['data'][$k]['service_config'][$v2['serv_type']]['time_end'] = date('Y-m-d', $v2['time_end']);
                        }
                        $data['data'][$k]['service_config'][$v2['serv_type']]['supplier_id'] = $suppliers[$v2['serv_type']] ?? [];
                        $data['data'][$k]['service_config'][$v2['serv_type']]['serc_type'] = @PRODUCT_SERV_TYPE[$v2['serv_type']]['name'] ?? '';
                        $data['data'][$k]['service_config'][$v2['serv_type']]['salesman_id'] = $salesmanArr[$v2['serv_type']]['salesman_id'] ?? [];
                        $data['data'][$k]['service_config'][$v2['serv_type']]['salesman_true_name'] = $salesmanArr[$v2['serv_type']]['salesman_true_name'] ?? '';
                    }
                }
                unset($data['data'][$k]['serviceConfig']);
                unset($data['data'][$k]['mobileSupplier']);
                unset($data['data'][$k]['supplier']);
                unset($data['data'][$k]['agentSalesman']);
                $data['data'][$k]['mobile_supplier_ids'] = json_decode($v['mobile_supplier_ids'], true) ?? [];
            }
        }

        return success('', $data);
    }

    /**
     * @api {POST} /admin/agentNew/save 代理商新增保存
     */
    public function save(Request $request)
    {
        $rules = [
            'company_name' => 'require',
            'username' => 'require',
            'mobile' => 'require',
            'password' => 'require|min:8|max:16|regex:/(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,16}/',
            'settle_type' => 'require',
            'config' => 'require',
            'link_type' => 'require',
        ];
        $messages = [
            'require' => '代理商基础信息必填',
            'config' => '配置信息必填',
            'password.min' => '密码长度不能小于8',
            'password.max' => '密码长度不能大于16',
            'password.regex' => '密码格式不正确',
        ];
        $paramBase = $request->only(['company_name', 'is_relation', 'link_type', 'settle_type', 'config', 'status', 'username', 'mobile', 'password', 'ip_address' => '', 'is_short_chain']);

        // 针对密码 处理
        if ($id = $request->param('id', 0)) {
            unset($rules['password']); // 编辑的时候不做密码必传校验
            if (empty($paramBase['password'])) { // 编辑时候不每天写密码则 不会更新免密的相关字段
                unset($paramBase['password']);
            }
        }
        if ($msg = dmjValidate($rules, $messages, $paramBase)) {
            return fail($msg);
        }
        if (!empty($paramBase['password'])) {
            $paramBase['password'] = password_hash($paramBase['password'], PASSWORD_DEFAULT);
        }


        $param['service_config'] = $paramBase['config'];
        unset($paramBase['config']);
        // 处理时间， 赋值 serv_type
        unset($param['service_config'][0]);
        foreach ($param['service_config'] as $k => $v) {
            $param['service_config'][$k]['serv_type'] = $k;
            if (!empty($v['time_end'])) {
                $param['service_config'][$k]['time_end'] = strtotime($v['time_end']);
            }

            // 话费折扣区分运营商: 移动，电信，联通
            if ($k === PRODUCT_MOBILE_SERV) {
                $v['serv_type'] = $k;
                $v['discount_fast_all'][0] = 0;
                $v['discount_slow_all'][0] = 0;
                for ($i = 1; $i < 4; $i++) {
                    $v['discount_fast_all'][$i] = $v['discount_fast_' . $i] ?? 0;
                    $v['discount_slow_all'][$i] = $v['discount_slow_' . $i] ?? 0;
                    unset($v['discount_fast_' . $i]);
                    unset($v['discount_slow_' . $i]);
                }
                $v['discount_fast'] = max($v['discount_fast_all']);
                $v['discount_slow'] = max($v['discount_slow_all']);
                $v['discount_fast_all'][0] = $v['discount_fast'];
                $v['discount_slow_all'][0] = $v['discount_slow'];
                array_walk($v['discount_fast_all'], 'my_number_format');
                array_walk($v['discount_slow_all'], 'my_number_format');
                $v['discount_fast_all'] = json_encode($v['discount_fast_all']);
                $v['discount_slow_all'] = json_encode($v['discount_slow_all']);
                $param['service_config'][$k] = $v;
            }
        }

        $param['base'] = $paramBase;
        unset($paramBase);
        $agentService = new AgentService();
        // 处理入库流程
        $res = $agentService->save($param, $id);
        if ($res['code']) {
            return fail($res['msg'], $res['code'], $res['data']);
        }

        return success();
    }

    /**
     * @api {GET} /admin/agentNew/read 代理商信息获取
     */
    public function read($id)
    {
        $data = Model::with('serviceConfig')->field(['id', 'username', 'company_name', 'password', 'mobile', 'ip_address'])->find($id)->toArray();
        // todo 去除密码 app_key等字段信息
        $serviceConfig = $data['serviceConfig'];
        unset($data['serviceConfig']);
        if ($serviceConfig) {
            foreach ($serviceConfig as $k => $v) {
                $data['service_config'][$v['serv_type']] = $v;
            }
        }
        $data['password'] = ''; // 屏蔽密码

        return success('', $data);
    }

    /**
     * @api {POST} /admin/agentNew/getServSupplier 业务对应供应商
     */
    public function getServSupplier(Request $request)
    {
        if ($sevType = $request->param('serv_type')) {
            $list = BaseSupplier::where('serv_type', $sevType)->where('agent_id', 0)->field('id,name,serv_type')->select();
        } else {
            $list = BaseSupplier::field('id,name,serv_type')->whereNotNull('serv_type')->where('agent_id', 0)->select();
        }
        $result = [];
        if ($list->isEmpty()) {
            $result = [];
        } else {
            $list = $list->toArray();
            foreach ($list as $k => $v) {
                $result[$v['serv_type']][] = ['label' => $v['name'], 'value' => $v['id']];
            }
        }

        // 话费供应商查询
        $result[PRODUCT_MOBILE_SERV] = [];
        $list = MobileSupplier::fieldRaw('id, name, discount_slow, discount_fast')->where('is_deleted', 0)->select();
        if (!$list->isEmpty()) {
            $list = $list->toArray();
            foreach ($list as $k => $v) {
                $result[PRODUCT_MOBILE_SERV][] = ['label' => $v['name'] . '(' . $v['discount_slow'] . '/' . $v['discount_fast'] . ')', 'value' => $v['id']];
            }
        }

        return success('', $result);
    }

    /**
     * @api {POST} /admin/agentNew/formServ 业务类型
     */
    public function formServ()
    {
        $servList = PRODUCT_SERV_TYPE;
        // 业务下折扣 对于
        $subList = ServiceSub::field(['serv_type', 'sub_type', 'name'])->whereNotIn('serv_type', [PRODUCT_MEAL_SERV])->select()->toArray();
        foreach ($subList as $v) {
            unset($servList[$v['serv_type']]['orderName']);
            if (!isset($servList[$v['serv_type']])) {
                continue;
            }
            switch ($v['sub_type']) {
                case 1:
                    $v['sub_name'] = '慢充';
                    $v['sub_field'] = 'discount_slow';
                    break;
                case 2:
                    $v['sub_name'] = '快充';
                    $v['sub_field'] = 'discount_fast';
                    break;
                case 3:
                    $v['sub_name'] = '过期时间';
                    $v['sub_field'] = 'time_end';
                    break;
                case 4:
                    $v['sub_name'] = '收益模式';
                    $v['sub_field'] = '';
                    break;
                case YIDONG_SLOW: // 移动慢充
                case LIANTONG_SLOW: // 联通慢充
                case DIANXIN_SLOW: // 电信慢充
                    $v['sub_field'] = 'discount_slow_' . substr($v['sub_type'], 1);
                    $v['sub_name'] = $v['name'];
                    break;
                case YIDONG_FAST: // 移动快充
                case LIANTONG_FAST: // 联通快充
                case DIANXIN_FAST: // 电信快充
                    $v['sub_field'] = 'discount_fast_' . substr($v['sub_type'], 1);
                    $v['sub_name'] = $v['name'];
                    break;
                default:
                    $v['sub_name'] = $v['name'];
                    $v['sub_field'] = 'value';
                    break;
            }
            $servList[$v['serv_type']]['sub'][] = $v;
        }

        return success('', $servList);
    }

    /**
     * @api {GET} /admin/agentNew/balance 代理余额
     */
    public function balance(Request $request)
    {
        $where = [];
        $param = input('post.');
        if (!empty($param['created_from'])) {
            $where[] = ['balance_last_updated_at', '>=', $param['created_from']];
        }
        if (!empty($param['created_end'])) {
            $where[] = ['balance_last_updated_at', '<=', $param['created_end'] . ' 23:59:59'];
        }
        $name = trim($param['name'] ?? '');
        if ($name) {
            $where[] = ['username|company_name', 'like', '%' . $name . '%'];
        }
        $sortFields = ['recharge_amount', 'balance', 'withdraw_amount', 'profit_balance', 'total_profit', 'balance_last_updated_at'];
        if (!empty($param['sortField']) && !empty($param['sortOrder'])) {
            if (in_array($param['sortField'], $sortFields)) {
                if ('ascend' == $param['sortOrder']) {
                    $order = $param['sortField'] . ' asc';
                } else {
                    $order = $param['sortField'] . ' desc';
                }
            } else {
                $order = 'balance_last_updated_at desc, balance desc';
            }
        } else {
            $order = 'balance_last_updated_at desc, balance desc';
        }

        $list = Model::field('id, balance, profit_balance, recharge_amount, withdraw_amount,
        total_profit, balance_last_updated_at, username, company_name, settle_type')
            ->where($where)
            ->order($order);

        // 导出数据字段处理
        if (!empty($param['is_export'])) {
            $list = $list->select()->toArray();
            $res = [];
            $title = ['代理商名称', '公司名称', '当前账户余额', '累计充值', '当前佣金余额', '累计佣金总额', '累计提现', '最近变更时间'];
            foreach ($list as $v) {
                $res[] = [
                    $v['username'],
                    $v['company_name'] . "\t",
                    fen2yuan($v['balance']) . '',
                    fen2yuan($v['recharge_amount']) . '',
                    fen2yuan($v['profit_balance']) . '',
                    fen2yuan($v['total_profit']) . '',
                    fen2yuan($v['withdraw_amount']) . '',
                    $v['balance_last_updated_at'],
                ];
            }
            unset($list);
            $export = new Export;
            $name = '代理商余额';
            return $export->downloadExcel($title, $res, $name);
        }

        $list = $list->paginate($this->getPaginate())->toArray();

        return success('操作成功', $list);
    }

    /**
     * @api {GET} /admin/agentNew/balanceLog 代理余额变动详细
     */
    public function balanceLog(Request $request)
    {
        $listType = $request->param('list_type');
        if (!$listType || !in_array($listType, ['commission', 'charge'])) {
            return fail('非法参数');
        }
        if (!$request->param('agent_id')) {
            return fail('缺少必要参数');
        }

        $agentBalanceLogService = AgentBalanceLogService::make();
        if ($request->param('is_export')) { // 此时导出两个sheet
            // 导出
            $exportTitle = [
                'type' => '充值类型',
                'username' => '代理商',
                'company_name' => '公司名称',
                'old_balance' => '变动前余额',
                'amount' => '变动金额',
                'new_balance' => '变动后余额',
                'remark' => '备注',
                'created_at' => '变动时间',
            ];
            if ($listType == 'charge') {
                $list[0]['sheetname'] = '充值账户明细';
                $list[0]['title'] = $exportTitle;
                $list[0]['data'] = $agentBalanceLogService->agentIdBalanceTypeLog($request->param('agent_id'), $request->all(), 'charge');
            }

            if ($listType == 'charge' || $listType == 'commission') {
                $index = $listType == 'charge' ? 1 : 0;
                $list[$index]['sheetname'] = '佣金账户明细';
                $list[$index]['title'] = $exportTitle;
                $list[$index]['data'] = $agentBalanceLogService->make()->agentIdBalanceTypeLog($request->param('agent_id'), $request->all(), 'commission');
            }

            unset($exportTitle);

            return $agentBalanceLogService->collectionToMulitSheetExcel($list, '代理商账户明细');
        } else {
            $list = $agentBalanceLogService->agentIdBalanceTypeLog($request->param('agent_id'), $request->all(), $request->param('list_type'), 1);
            // 代理商余额相关
            $list['agent'] = Model::field(['balance', 'profit_balance', 'settle_type'])->where('id', $request->param('agent_id'))->find()->toArray();
        }

        return success('', $list);
    }

    /**
     * 代理商每日余额快照
     */
    public function dailyBalanceLog()
    {
        $params = input('post.');
        $model = new \app\admin\model\Agent;
        return $model->getDailyBalanceList($params);
    }

    /**
     * 代理列表
     */
    public function agentList()
    {
        $data = \app\model\Agent::query()->field(['username','company_name', 'id'])->where('status', \app\model\Agent::STATUS_ACTIVE)->select();

        return success('', $data);
    }
}
